package com.sprite.framework.entity.script;

import java.util.List;

import com.sprite.framework.entity.DataScriptStatement;
import com.sprite.framework.entity.EntityCondition;
import com.sprite.framework.entity.EntityException;
import com.sprite.framework.entity.condition.MultiOperateValue;
import com.sprite.framework.entity.model.ModelEntityView;

/**
 * <p>实体视图连接</p>
 *  JOIN
 * @author Jack
 *
 */
public final class EntityViewLink implements EntityFieldAliasBuilder, MultiOperateValue{
	protected String code;
	protected EntityAlias entityAlias;
	protected EntityView entityView;
	protected String alias;
	protected EntityCondition onCondition;

	public EntityViewLink(String code, EntityView entityView, String alias,
			EntityCondition onCondition) {
		this.code = code;
		this.alias = alias;
		this.entityView = entityView;
		this.onCondition = onCondition;
	}
	
	public EntityViewLink(String code, String entityName, String alias,
			EntityCondition onCondition) {
		this.code = code;
		this.alias = alias;
		this.entityAlias = new EntityAlias(entityName, alias);
		this.onCondition = onCondition;
	}

	@Override
	public boolean hasField(String field) {
		return getEntityFieldAliasBuilder().hasField(field);
	}

	@Override
	public String resolveFieldPath(String path) {
		return getEntityFieldAliasBuilder().resolveFieldPath(path);
	}

	@Override
	public EntityFieldAlias buildFieldAlias(String fieldName, String fieldAlias, EntityScriptFunction function) {
		return getEntityFieldAliasBuilder().buildFieldAlias(fieldName, fieldAlias, function);
	}

	@Override
	public List<EntityFieldAlias> buildAllFieldAlias() {
		return getEntityFieldAliasBuilder().buildAllFieldAlias();
	}
	
	private EntityFieldAliasBuilder getEntityFieldAliasBuilder() {
		if(entityView != null) {
			return entityView;
		}
		
		if(entityAlias != null) {
			return entityAlias;
		}
		
		return null;
	}

	@Override
	public void makeStatement(DataScriptStatement statement, ModelEntityView modelViewEntity) throws EntityException {
		if(entityView != null) {
			statement.append(" (");
			entityView.makeStatement(statement, modelViewEntity);
			statement.append(" )");
		}
		
		if(entityAlias != null) {
			entityAlias.makeStatement(statement, modelViewEntity);
		}
		
		statement.append(" AS ").append(alias);
	}
}
